<!--
//
// GCountDown.vue
// hs-admin
//
// Created by 区区电脑 on 2023/04/27.
//
-->
<template>
    <div class="GCountDown">
        <div v-if="state.isEnd">{{ endText }}</div>
        <div v-else>{{ state.text }}</div>
    </div>
</template>

<script setup>
import {ref, reactive, computed, onMounted} from "vue";
import {useStore} from "vuex";
import {useRouter} from "vue-router";

const props = defineProps({
    endTime: {
        type: String,
        default: () => ""
    },
    endText: {
        type: String,
        default: () => ""
    }
});
const emits = defineEmits(["end"]);

// 路由
const router = useRouter();
// store
const store = useStore();
const state = reactive({
    text: "",
    isEnd: false
})

// 格式化倒计时
function format() {
    // 当前时间到结束时间的时间间隔 秒
    const duration = (new Date(props.endTime).getTime() - new Date().getTime()) / 1000;
    // 一天是多少秒
    const daySecond = 1 * 60 * 60 * 24
    // 提取天数
    const days = parseInt(duration / daySecond);
    // 天数的余数 秒
    const days_ = duration - days * daySecond;

    // 一小时是多少秒
    const hourSecond = 1 * 60 * 60;
    // 提取小时
    const hours = parseInt(days_ / hourSecond);
    // 小时的余数 秒
    const hours_ = days_ - hours * hourSecond;

    // 一分钟是多少秒
    const minuteSecond = 1 * 60;
    // 提取分钟
    const minutes = parseInt(hours_ / minuteSecond);
    // 分钟的余数 秒
    const minutes_ = parseInt(hours_ - minutes * minuteSecond);

    // 组装倒计时文本
    let text = "";
    if (days > 0) {
        text += ` ${days} 天`
    }
    if (hours > 0) {
        text += ` ${hours} 小时`
    }
    if (minutes > 0) {
        text += ` ${minutes} 分钟`
    }
    text += ` ${minutes_} 秒`
    state.text = text;
}

let timer;
function init() {
    if (timer) {
        clearInterval(timer)
        timer = null;
    }
    if (new Date().getTime() >= new Date(props.endTime).getTime()) {
        state.isEnd = true;
        return;
    }
    format();
    timer = setInterval(() => {
        format()
        if (new Date().getTime() >= new Date(props.endTime).getTime()) {
            clearInterval(timer)
            timer = null;
            state.isEnd = true;
            emits("end")
            return;
        }
    }, 1000)
}

onMounted(() => {
    init()
})
</script>

<style lang="scss" scoped>
.GCountDown {
    font-size: 14px;
    color: var(--el-color-warning);
}
</style>
